<template>
  <div class="right">
    <div style="border-bottom:1px solid #e4e4e4">
      <div class="flex f-r-sb f-a-c">
        <el-dropdown trigger="click" @command="versionChange" v-if="!showLoadingOrRefresh">
          <el-button type="text ml20"><i class="fa fa-navicon mr5"></i>{{$ts('Version')}}：{{currentVersion.label}}
          </el-button>
          <template #slot:dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="item.value" v-for="item in versionOptions" :key="item.value">
                <span :class="currentVersion.value == item.value ? 'text-green':''">{{item.label}}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div class="flex flex1 flex-row-c f-a-c no-margin pd-t4 pd-b4">
          <el-button v-if="CanuUndo&& undoList.length != 0" type="text" @click="undoSchedule" :loading="undoLoading"
            class="mr10">
            <i class="fa fa-undo mr5  text-yellow"></i><span class="text-yellow">{{$ts('undo')}}</span>
          </el-button>
          <el-dropdown trigger="click" @command="dropDown" v-if="currentVersion.IsEdit && !showLoadingOrRefresh">
            <el-button type="text mr10"><i class="fa fa-navicon mr5"></i>{{$ts('LineBodyScheme')}}</el-button>
            <template #slot:dropdown>

              <el-dropdown-menu>
                <el-dropdown-item :command="item.value" v-for="item in planList" :key="item.value">
                  <span :class="currentPlan.value == item.value ? 'text-green':''">{{item.label}}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="0" divided><span class="text-blue">{{$ts('myPlan')}}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="1" divided><span class="text-yellow">{{$ts('clearSelected')}}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <template v-if="showLoadingOrRefresh">
            <el-button type="text" @click="LoadSchedule" :loading="LoadScheduleLoading">
              <i class="el-icon-stopwatch  text-yellow"></i><span class="text-yellow">{{$ts('Loading')}}</span>
            </el-button>
            <el-button type="text " @click="ReductionSchedule" :loading="ReductionScheduleLoading">
              <i class="fa fa-undo  text-yellow mr5"></i><span class="text-yellow">{{$ts('Reduction')}}</span>
            </el-button>
          </template>
          <el-button type="text primary" @click="zoomChange(true)">
            <i class="el-icon-zoom-in mr5"></i>{{$ts('viewMagnification')}}
          </el-button>
          <el-button type="text primary" @click="zoomChange()">
            <i class="el-icon-zoom-out mr5"></i>{{$ts('ViewToNarrow')}}
          </el-button>
          <el-button type="text primary" @click="ShowPercentDialog">
            <i class="fa fa-percent mr5"></i>{{$ts('AchievementRateStatistics')}}
          </el-button>
          <el-button type="text primary" @click="exportDialogOpen">
            <i class="fa fa-download mr5"></i>{{$ts('TheDataDownload')}}
          </el-button>
          <el-button type="text primary" @click="goToSchedulingTable">
            <i class="fa fa-table mr5"></i>{{$ts('switchingTableFigure')}}
          </el-button>
          <el-button type="text primary" @click="deliveryDialogVisible = true">
            <i class="el-icon-upload mr5"></i>{{$ts('push')}}
          </el-button>
          <el-button type="text primary" @click="showSearch = !showSearch">
            <i class="fa mr5"
              :class="showSearch?'fa-angle-double-up' :'fa-angle-double-down'"></i>{{showSearch?$ts('PackUpTheQuery')
            :$ts('MoreQueries') }}
          </el-button>
        </div>
        <el-radio-group v-model="selectColor" size="mini" class="mr20">
          <el-tooltip placement="bottom" effect="light">
            <el-radio-button :label="0">{{$ts('DeliveryStatus')}}</el-radio-button>
            <template #content>
              <div class="pd4">
                <div class="mr-b4 flex  flex-a-c">
                  <el-tag color="#F56C6C" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('TheDeliveryDateCannotBeMet')}}</span>
                </div>
                <div class="mr-b4 flex  flex-a-c">
                  <el-tag color="#67C23A" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('MeetTheDeliveryTimeAheadOfSchedule')}}</span>
                </div>
                <div class="mr-b4 flex  flex-a-c">
                  <el-tag color="#409EFF" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('On_the_day_of_production_on_the_day_of_shipment')}}</span>
                </div>
                <div class="mr-b4 flex  flex-a-c">
                  <el-tag color="#E6A23C" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('Completion_less_than_delivery_date_morethan7days')}}</span>
                </div>
                <div class="mr-b4 flex  flex-a-c">
                  <el-tag color="#666" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('UncompletedWorkOrderForScheduling')}}</span>
                </div>
              </div>
            </template>
          </el-tooltip>
          <el-tooltip placement="bottom" effect="light">
            <el-radio-button :label="1">{{$ts('TheRepairOrderOfOldAndNew')}}</el-radio-button>
            <template #content>
              <div class="pd4">
                <div class="mr-b4 flex flex-a-c">
                  <el-tag color="#409EFF" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('TheNewWorkOrder')}}</span>
                </div>
                <div class="mr-b4 flex flex-a-c">
                  <el-tag color="#666" size="mini"></el-tag>
                  <span class="lineHeight24">{{$ts('TheOldOrder')}}</span>
                </div>
              </div>
            </template>
          </el-tooltip>
        </el-radio-group>
      </div>
      <el-collapse-transition>
        <div class="flex flex-row-c f-s-c " v-show="showSearch">
          <div class="ml20 mr10" style="line-height:32px">{{$ts('LineCode')}}</div>
          <el-select v-model="form.select" style="width: 180px" filterable clearable>
            <el-option v-for="item in lineCodeOptions" :key="item.id" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <div class="ml20 mr10" style="line-height:32px">{{$ts('repairOrder')}}</div>
          <el-input style="width: 180px" v-model="form.workOrder"></el-input>
          <div class="ml20 mr10" style="line-height:32px">{{$ts('model')}}</div>
          <el-input style="width: 180px" v-model="form.code"></el-input>
          <el-button class="ml20" type="primary" @click="search">{{$ts('search')}}</el-button>
        </div>
      </el-collapse-transition>
    </div>
    <div v-loading="pageLoading" class="flex" :style="{height:`calc(100% - 40px - ${showSearch?36:0 }px)`}">
      <div style="width:65px;height:100%;overflow-y:auto">
        <div class="icon-btn" v-if="currentVersion.IsEdit" @click="SaveApsScheduleTask"><i class="fa fa-save"
            :class="needSave?'text-red':'text-gray'"></i>
          <div class="title" :class="needSave?'text-red':'text-gray'">{{$ts('SaveTheSchedule')}}</div>
        </div>
        <div class="icon-btn" v-if="currentVersion.IsEdit" @click="clickHalbModal"><i
            class="el-icon-s-data icon text-blue"></i>
          <div class="title text-blue">计算半品交货日</div>
        </div>
        <!-- <div class="icon-btn" v-if="currentVersion.IsEdit" @click="clickHalbModal"><i class="el-icon-s-data icon text-blue"
          ></i>
          <div class="title text-blue" >按方案将未排工单排至线体</div>
        </div> -->
        <div class="flex flex-col" v-if="currentVersion.IsEdit">
          <div class="icon-btn mt5" @click="addWorkOrder"><i class="fa fa-file-o icon text-blue"></i>
            <div class="title text-blue">{{$ts('newWorkOrder')}}</div>
          </div>
          <div class="icon-btn" @click="ApsScheduleTaskSort"><i class="fa fa-sort-amount-asc icon text-blue"></i>
            <div class="title text-blue">{{$ts('AutomaticSorting')}}</div>
          </div>
          <div class="icon-btn" @click="acrossLineGantt(maskList)"><i
              class="iconfont icon-igw-l-sort-2 icon text-blue"></i>
            <div class="title text-blue">{{$ts('CrossLineRearrangement')}}</div>
          </div>
          <div class="icon-btn" @click="RefreshWoSapInfo"><i class="fa fa-level-down icon text-blue"></i>
            <div class="title text-blue">{{$ts('DataSynchronization')}}</div>
          </div>
          <div class="icon-btn" @click="recalculate"><i class="fa fa-calculator icon text-blue"></i>
            <div class="title text-blue">{{$ts('Recalculate')}}</div>
          </div>

          <el-dropdown trigger="click" placement="bottom-start" @command="snapShotChange" :loading="snapShotLoading">
            <div class="icon-btn">
              <i class="fa fa-camera icon text-blue" :title="$ts('TheSnapshotManagement')"></i>
              <div class="title text-blue">{{$ts('TheSnapshotManagement')}}</div>
            </div>
            <template #slot:dropdown>

              <el-dropdown-menu>
                <el-dropdown-item :command="0" divided><span class="text-blue">{{$ts('SaveTheSnapshot')}}</span>
                </el-dropdown-item>
                <el-dropdown-item :command="1" divided><span class="text-yellow">{{$ts('ToViewASnapshot')}}</span>
                </el-dropdown-item>
                <!-- <el-dropdown-item :command="2" divided><span class="text-yellow">快照对比</span>
                </el-dropdown-item> -->
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <div class="icon-btn" @click="addSchedule"><i class="iconfont icon-piliangshengcheng icon text-yellow"></i>
            <div class="title text-yellow">{{$ts('AddCalendarsInBatches')}}</div>
          </div>
          <div class="icon-btn" @click="togetherSchedule"><i class="iconfont icon-xianghujiaohuan icon text-yellow"></i>
            <div class="title text-yellow">{{$ts('CalendarInteradjustment')}}</div>
          </div>
          <div class="icon-btn" @click="deleteMoreSchedule"><i class="iconfont icon-batch-del icon text-yellow"></i>
            <div class="title text-yellow">{{$ts('CalendarBatchDelete')}}</div>
          </div>
        </div>
      </div>
      <div ref="gantt" class="ganttCss"></div>
    </div>
    <!-- 新增工单 -->
    <z-table-add-project ref="zTableAddProject" :oldTask="maskList" @submit="getRowData" :version="currentVersion.value"
      v-model="addWorkOrderFormVisible" :portLoading="pageLoading" :isModify="needSave"
      @saveSchedule="SaveApsScheduleTask" @excelSucces="excelSucces">
    </z-table-add-project>
    <!-- 达成率统计 -->
    <el-dialog :title="$ts('AchievementRateStatistics')" v-model="percentDialogShow" width="60%">
      <el-table :data="percentData" style="width: 100%">
        <el-table-column prop="LineCode" :label="$ts('SolidLine')" width="75" align="center">
        </el-table-column>
        <el-table-column prop="WorkNum" :label="$ts('WorkingOdd')" width="75" align="center">
        </el-table-column>
        <el-table-column prop="ok_cnt" :label="$ts('CanBeCompletedOnTime')" width="120" align="center">
        </el-table-column>
        <el-table-column prop="ng_cnt" :label="$ts('RiskOfDelivery')" width="90" align="center">
        </el-table-column>
        <el-table-column prop="ok_pct" :label="$ts('AchievableRateOnTime')" width="110" align="center">

          <template #slot:scope>
            <span>{{parseInt(scope.row.ok_pct*100)}}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="WorkQty" :label="$ts('TotalNumberOfProducts')" width="75" align="center">
        </el-table-column>
        <el-table-column prop="ok_reduce" :label="$ts('CompletionOnTime')" width="120" align="center">
        </el-table-column>
        <el-table-column prop="ng_reduce" :label="$ts('DeliveryRiskNumber')" width="120" align="center">
        </el-table-column>
        <el-table-column prop="ok_reduce_pct" :label="$ts('ProductAchievementRate')" width="120" align="center">
          <template #slot:scope>
            <span>{{parseInt(scope.row.ok_reduce_pct*100)}}%</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 行事历批量生成 -->
    <!-- <schedule-batch-add :addData="addScheduleData" v-model="scheduleBatchAddVisible"
      @afterSubmit="afterAddSchedule"></schedule-batch-add> -->
    <!-- 编辑行事历 -->
    <!-- <schedule-batch-edit ref="scheduleBatchEdit" :addData="editScheduleData" v-model="scheduleBatchEditVisible"
      @afterSubmit="afterAddSchedule"></schedule-batch-edit> -->
    <!-- 行事历互调 -->
    <!-- <schedule-batch-together :addData="togetherScheduleData" v-model="scheduleBatchTogetherVisible"
      @afterSubmit="afterAddSchedule"></schedule-batch-together> -->
    <!-- 行事历批量删除 -->
    <!-- <schedule-batch-delete :addData="deleteScheduleData" v-model="scheduleBatchDeleteVisible"
      @afterSubmit="afterAddSchedule"></schedule-batch-delete> -->
    <!-- 跨线重排 -->
    <!-- <schedule-batch-cross :addData="crossScheduleData" v-model="scheduleBatchCrossVisible"
      @afterSubmit="getRowData"></schedule-batch-cross> -->

    <!-- 行事历点击展示 -->
    <!-- <foreman-detail :calendarType="foremanDetailRow.shifttype" :LineCode="foremanDetailRow.LineCode"
      :row="foremanDetailRow" v-model="foremanDetailVisible" :ScheduleId="foremanDetailRow.ScheduleId">
    </foreman-detail> -->

    <!-- 展示班次明细 -->
    <el-dialog :title="$ts('ClassShowsThatFine')" v-model="showVisibleDialog" width="60%"
      @close="showVisibleDialog = false">
      <el-table :data="scheduleList" style="width: 100%">
        <el-table-column prop="ClockInType" :label="$ts('type')">
          <template #slot:scope>
            <span>{{[$ts('NormalWork'),$ts('Rest'),$ts('WorkOvertime')][scope.row.ClockInType-1] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="StartTime" :label="$ts('StartTime')">
          <template #slot:scope>
            <span>{{scope.row.StartTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="EndTime" :label="$ts('EndTime')">
          <template #slot:scope>
            <span>{{scope.row.EndTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Hours" :label="$ts('Minutes')">
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 导出弹窗 -->
    <el-dialog :title="$ts('ExportDataSelection')" :modal="true" :modal-append-to-body="true"
      v-model="exportDialogVisible" :close-on-click-modal="false" :show-close="true" :close-on-press-escape="true">
      <div style="margin-top:15px;">
        请选择导出方式
      </div>
      <div style="margin-top:15px;">
        <el-select style="width:100%" v-model="exportMethod" :placeholder="'请选择导出方式'">
          <el-option label="按区域" :value="0"></el-option>
          <el-option label="按线体" :value="1"></el-option>
        </el-select>
      </div>
      <template v-if="exportMethod == 0">
        <div style="margin-top:15px;">
          请选择导出区域
        </div>
        <div style="margin-top:15px;">
          <el-select style="width:100%" v-model="exportSelectedArea" filterable :placeholder="'请选择导出区域'">
            <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </template>
      <template v-if="exportMethod == 1">
        <div style="margin-top:15px;">
          {{$ts('canInputTheMachineType')}}
        </div>
        <div style="margin-top:15px;">
          <el-select style="width:100%" v-model="exportSelectedLines" filterable clearable multiple
            :placeholder="$ts('PleaseSelectTheLine')">
            <el-option v-for="item in lineCodeOptions" :key="item.id" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </template>
      <div style="margin-top:15px;">
        {{$ts('SelectTheSchedulingVersion')}}
      </div>
      <div>
        <el-select style="width:100%" v-model="exportSelectedVersion" filterable clearable
          :placeholder="$ts('PleaseSelectTheVersion')">
          <el-option v-for="item in versionOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <template #slot:footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="exporting" @click="exportData">{{$ts('export')}}</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- <my-plan v-model="planDialog" :list="planList" ref="planDialog">
    </my-plan> -->
    <!-- 快照 -->
    <snapshot-dialog v-model:pageLoad="pageLoading" @afterData="afterSnapShotData" v-model="snapshotShowDialog"
      :ApsScheduleId="currentVersion.value">
    </snapshot-dialog>
    <!-- 快照对比 -->
    <!-- <snapshot-comparison :oldList="percentData" :visible.sync="SnapshotComparisonShowDialog"
      :ApsScheduleId="currentVersion.value">
    </snapshot-comparison> -->
    <!-- 推送排程 -->
    <!-- <delivery-schedule :name="$ts('DeliverySchedule')" :ApsScheduleId="currentVersion.value"
      v-model="deliveryDialogVisible" @openEmailLineSelect="openEmailLineSelect">
    </delivery-schedule> -->
    <!-- 自动排序选择时间 -->
    <el-dialog :title="$ts('SelectTheSortStartDate')" v-model="autoSortVisibleDialog" width="25%"
      @close="autoSortVisibleDialog = false">
      <div style="width:100%">
        <label for="" style="max-width:300px">
          {{$ts('Date')}}:
        </label>
        <el-date-picker style="width:calc(100%-300px)" v-model="autoSortDateStartTime" type="date"
          value-format="yyyy-MM-dd" format="yyyy-MM-dd" :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <template #slot:footer>

        <span class="dialog-footer">
          <el-button type="primary" :loading="autoSortLoading" @click="autoSortAps">{{$ts('Sorting')}}</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 推送完成发送邮件 线体选择 -->
    <!-- <send-email-dialog v-model:showVisibleDialog="emailexportDialogVisible"
      :lineCodeOptions="lineCodeOptions.map(a =>a.value)"></send-email-dialog> -->
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin.js'
import Gantt from '@/uitils/gantt/frappe-gantt.js'
import _ from 'lodash'
import dayjs from 'dayjs'
import XLSX from 'xlsx'
import XLSXS from 'xlsx-style'
import FileSaver from 'file-saver'
import { mapGetters } from 'vuex'

// import MyPlan from '@/views/components/MyPlan'
// import zTableAddProject from './components/addProject.vue'
// import ScheduleBatchAdd from './components/scheduleBatchAdd.vue'
// import ScheduleBatchEdit from './components/scheduleBatchEdit.vue'
// import ScheduleBatchTogether from './components/scheduleBatchTogether.vue'
// import ScheduleBatchDelete from './components/scheduleBatchDelete.vue'
// import ScheduleBatchCross from './components/scheduleBatchCross.vue'
// import ForemanDetail from './components/ForemanDetail.vue'
// import SnapshotDialog from './components/snapshotDialog.vue'
// import SnapshotComparison from './components/SnapshotComparison.vue'
// import DeliverySchedule from './components/DeliverySchedule.vue'
// import sendEmailDialog from './components/sendEmailDialog.vue'

export default {
  mixins: [commonMixin],
  name:'apsGantt',
  components: {
    zTableAddProject,
    // MyPlan,
    // ScheduleBatchAdd,
    // ScheduleBatchEdit,
    // ScheduleBatchTogether,
    // ScheduleBatchDelete,
    // ScheduleBatchCross,
    // ForemanDetail,
    // SnapshotDialog,
    // SnapshotComparison,
    // DeliverySchedule,
    // sendEmailDialog,
  },
  data() {
    return {
      pageLoading: false,
      name: '方案',
      gantt: null,
      currentVersion: {
        IsEdit: true,
      },
      currentPlan: {},
      maskList: [],
      rows: [],
      workhours: [],
      taskDate: [],
      viewModes: ['Fourth Day', 'Third Day', 'Half Day', 'Day'],
      currentView: 'Half Day',
      showMore: true,
      form: {
        select: '',
        workOrder: '',
        code: '',
      },
      selectColor: 0,
      lineOptions: [],
      planList: [],
      planDialog: false,
      editFormVisible2: false,
      tableProps: {
        border: true,
        opsColWith: 80,
        index: false,
        heightControl: false,
        tableHeight: 220,
        NOscrollBar: true,
        hideOperations: true,
        selection: true,
      },
      muliTableList: [],
      data: {},
      buttonShow: true,
      percentData: [],
      percentDialogShow: false,
      showRight: false,
      showSearch: false,
      // 选中左侧框
      muliBoxList: [],
      lineCodeOptions: [],
      taskMulitp: [],
      canDeleteTask: [],
      Remark: '',
      versionOptions: [],

      // 批量新增行事历
      scheduleBatchAddVisible: false,
      addScheduleData: {},

      // 编辑行事历
      editScheduleData: {},
      scheduleBatchEditVisible: false,

      // 行事历互调
      togetherScheduleData: {},
      scheduleBatchTogetherVisible: false,

      // 行事历批量删除
      deleteScheduleData: {},
      scheduleBatchDeleteVisible: false,
      // 跨线重排
      crossScheduleData: {},
      scheduleBatchCrossVisible: false,

      // 展示班次明细
      showVisibleDialog: false,
      scheduleList: [],

      // 新建工单
      addWorkOrderFormVisible: false,
      needSave: false,

      // 展示领班信息弹框
      foremanDetailVisible: false,
      foremanDetailRow: {},

      //导出
      exportDialogVisible: false,
      exportInputModel: '',
      exportMethod: 0,
      exportSelectedArea: '',
      exportSelectedLines: [],
      exportSelectedVersion: '',
      exporting: false,
      areaOptions: [],

      // 快照展示
      snapshotShowDialog: false,
      snapShotLoading: false,
      // 快照对比
      SnapshotComparisonShowDialog: false,

      // 载入loading
      LoadScheduleLoading: false,
      ReductionScheduleLoading: false,
      // 撤销loading
      undoLoading: false,
      CanuUndo: false,
      undoList: [],
      // 推送排程dialog
      deliveryDialogVisible: false,

      // 展示快照还原载入
      showLoadingOrRefresh: false,

      // 自动排序时间
      autoSortVisibleDialog: false,
      autoSortDateStartTime: '',
      autoSortLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 //如果没有后面的-8.64e7就是不可以选择
        },
      },
      // 邮件通知loading
      emailPushLoading: false,
      emailexportDialogVisible: false,
      //半品交货日
      halbModalVisible: false,
      productQuery: {
        page: 1,
        size: 500,
        queryString: '',
      },
      productsCodeOptions: [],
      halbData: { MatList: [], SyncFlag: 0, Plan: '', Days: null },
      halbSubmitLoading: false,
      currentPlan: '',
      halbCalWoComponents: [],
      halbCalInventorys: [],
      halbCalWorkOrders: [],
      deletedScheduleTasks: [],
    }
  },
  filters: {
    dataTime: function (val) {
      return dayjs(val).format('HH:mm')
    },
  },
  watch: {
    selectColor(v) {
      this.pageLoading = true
      this.gantt.changeOptionsSelectColor(v)
      setTimeout(() => {
        this.pageLoading = false
      }, 1000)
    },
  },
  created: async function () {
    this.researchProduct()
    //获取方案选项
    this.getPlanOptions()
    //获取我管理的线体列表
    await this.getMyLineCode()
    //生成泳道数据
    this.rows = this.lineCodeOptions.map((x) => {
      return {
        id: x.value,
        row_id: x.value,
        name: x.value,
      }
    })
    //获取排程版本
    await this.GetApsScheduleList()
    //默认选择最新版本
    await this.versionChange(this.versionOptions[0].value)
  },
  mounted: async function () {},
  methods: {
    planDaysChange(v) {
      if (!v) return
      this.$http.get(this.$api.schedue + 'GetDaysByPlan', { id: v }).then(
        (r) => {
          if (r.Data) this.halbData.Days = Number(r.Data)
        }
      )
    },
    //按方案将半品工单排至线体

    //半品交货日点击弹出模态框可选择急单
    clickHalbModal() {
      this.halbModalVisible = true
      this.halbData.Plan =
        this.currentPlan != null ? this.currentPlan.value : ''
    },
    researchProduct(val) {
      this.productQuery.page = 1
      this.getProductList(val)
    },
    //半品获取机种码
    getProductList(val) {
      if (val) {
        this.productQuery.page = 1
        this.productQuery.queryString = val
      } else {
        this.productQuery.queryString = ''
      }
      this.http.get(this.$api.leanBaseModelCodeContoller + 'getlist', {
        ...this.productQuery,
        modelTypeNo: this.data.ProductsCategory || '',
        projectName: this.data.ProductsPlan || '',
      }).then((r) => {
        this.productsCodeOptions = r.Data.map((x) => {
          return {
            label: x.ModelNo,
            value: x.ModelNo,
          }
        })
        if (
          this.productsCodeOptions.length == 0 &&
          this.productQuery.queryString
        ) {
          this.productsCodeOptions.push({
            label: this.productQuery.queryString,
            value: this.productQuery.queryString,
          })
        }
      })
    },
    //计算交货日提交
    calHalbDateSubmit() {
      if (!this.halbData.Plan && this.halbData.MatList.length <= 0) {
        this.$message.error('必须选择一个方案或者选择急单机种码')
        return
      }
      let planArray = !this.halbData.Plan ? [] : [this.halbData.Plan]
      this.halbSubmitLoading = true
      this.http.post(
        this.$api.schedue + 'HandCalHalbDeliveryDate',
        { PlanList: planArray, ...this.halbData },
      )
        .then((r) => {
          this.halbSubmitLoading = false
          this.halbData.MatList = []
        })
        .catch((e) => {
          this.halbSubmitLoading = false
        })
    },
    exportDialogOpen() {
      this.getAreaOptions()
      this.exportSelectedArea = ''
      this.exportSelectedVersion = ''
      this.exportSelectedLines = []
      this.exportDialogVisible = true
    },
    // 获取区域字典值
    getAreaOptions() {
      this.http.post(
        this.$api.dict + 'GetDictionaryByCode',
        ['exportArea'],
        'post'
      ).then((r) => {
        this.areaOptions = r.Data.find(
          (c) => c.DicCode == 'exportArea'
        ).lstDic.map((x) => {
          return {
            label: x.DicName,
            value: x.Id,
          }
        })
      })
    },
    // 获取版本号
    async GetApsScheduleList() {
      await this.http.get(this.$api.schedue + 'GetApsScheduleList').then(
        (r) => {
          this.versionOptions = r.Data.map((x) => {
            return {
              label: x.Version,
              value: x.Id,
              IsEdit: x.IsEdit,
            }
          })
        }
      )
    },
    // 版本切换
    async versionChange(v) {
      try {
        this.gantt.hide_popup()
        this.undoList = []
        this.CanuUndo = false
      } catch (error) {
        this.ReductionScheduleLoading = false
      }
      this.currentVersion = this.versionOptions.find((x) => x.value == v)
      await this.GetGanttChartData()
    },
    // 数据同步
    RefreshWoSapInfo() {
      if (this.muliBoxList.length == 0) {
        return this.$message.info('请选择实体线后操作')
      }
      let taskList = this.maskList.filter((x) =>
        this.muliBoxList.includes(x.LineCode)
      )
      if (taskList.length == 0) {
        return this.$message.info('当前实体线没有需要同步的工单')
      }
      this.pageLoading = true
      this.http.post(this.$api.schedue + 'RefreshWoSapInfo', taskList)
        .then((r) => {
          //this.getRowData(r.Data, false, false)
          this.pageLoading = false
        })
        .catch((r) => {
          this.pageLoading = false
        })
    },
    //更新界面线体数据
    async GetGanttChartData() {
      this.pageLoading = true
      if (this.rows.length == 0) {
        this.pageLoading = false
        this.$message.info('您没有管理的实体线,快联系生管添加吧')
        return
      }
      let { Data } = await this.http.post(
        this.$api.schedue + 'GetGanttChartData',
        {
          lineCodes: this.rows.map((x) => x.row_id),
          ApsScheduleId: this.currentVersion.value,
        },
      )
      Data.tasks.forEach((x) => {
        x.id = x.Id
        x.start = x.WorkingStartTime
        x.end = x.WorkingEndTime
        x.row_id = x.LineCode
        x.barType = 2
        x.custom_class = 'bar-milestone'
        x.Detail = Data.taskDates.filter((l) => l.TaskId == x.Id) || []
        x.WorkDate = x.Detail.length > 0 ? x.Detail[0].WorkDate : null
      })
      //行事历数据处理
      Data.lineCalendars.forEach((x) => {
        x.id = x.Id
        x.start = x.ShiftType
          ? dayjs(x.WorkDate).add(12, 'hours').format('YYYY-MM-DD HH:mm:ss')
          : x.WorkDate
        x.end = dayjs(x.start).add(12, 'hours').format('YYYY-MM-DD HH:mm:ss')
        x.row_id = x.LineCode
        x.barType = 1
        x.selectStatus = true
        x.custom_class = 'bar-milestone'
      })
      this.muliBoxList = [] //清空选中状态
      this.maskList = Data.tasks
      this.workhours = Data.lineCalendars
      this.taskDate = Data.taskDates
      this.pageLoading = false
      let options = {
        IsEdit: this.currentVersion.IsEdit,
        Holidays: Data.restDays,
      }
      if (this.gantt) {
        this.gantt.unselect_all()
        this.gantt.refresh(this.maskList, this.workhours, this.rows, options)
      } else this.init(options)
      this.needSave = false
      this.ReductionScheduleLoading = false
    },
    //计算达成率
    calculatedAchievementRate() {
      this.percentData = []
      for (let i = 0; i < this.rows.length; i++) {
        let datas = this.maskList.filter((x) => x.LineCode == this.rows[i].name)
        let WorkQty = 0,
          ok_cnt = 0,
          ng_cnt = 0,
          ok_pct = 100,
          ok_reduce = 0,
          ng_reduce = 0,
          ok_reduce_pct = 100
        if (datas.length) {
          datas.forEach((x) => {
            WorkQty += x.WorkQty
            if (x.FinishStatus == 0 || x.FinishStatus == 1) {
              ok_cnt++
              ok_reduce += x.WorkQty
            } else {
              ng_cnt++
              ng_reduce += x.WorkQty
            }
          })
          ok_pct =
            datas.length && ok_cnt
              ? parseFloat(ok_cnt / datas.length).toFixed(2)
              : 0
          ok_reduce_pct =
            WorkQty && ok_reduce
              ? parseFloat(ok_reduce / WorkQty).toFixed(2)
              : 0
        } else {
          ok_reduce_pct = 0
          ok_pct = 0
        }
        this.percentData.push({
          LineCode: this.rows[i].name,
          WorkNum: datas.length,
          ok_cnt,
          ng_cnt,
          ok_pct,
          WorkQty,
          ok_reduce,
          ng_reduce,
          ok_reduce_pct,
        })
      }
    },
    //初始化甘特图
    async init(options) {
      let default_options = {
        view_mode: this.currentView,
        move_task: this.moveData,
        vueSetScroll: this.vueSetScroll,
        menuClickHandle: this.menuClickHandle,
        // 左侧容器checkbox change事件 参数（value,item,index） //checked的值 绑定到当前行的row行对象 index 为当前下标
        boxChange: this.boxChange,
        // popup more 点击更多
        popupMoreClick: this.popupMoreClick,
        // 选中数据
        selectFormDatas: this.selectFormDatas,
        errorMessage: this.errorMessage,
        // 行事历点击事件
        barTypeOneClick: this.barTypeOneClick,
        selectColor: 0,
        IsEdit: true,
        autoBgColor: [
          ['#409EFF', '#67C23A', '#F56C6C', '#E6A23C'],
          ['#666', '#409EFF'],
        ], //工单状态色
        autoTimeBg: ['#78b9fb30', '#67c23a30'], // 白夜班时间状态色
        clickBgColor: [],
        menuList: ['保存排程', '自动排序', '快照备份'],
        barMenuList: [
          // '详细信息',
          // this.$ts('UPHAdjustment'),
          this.$ts('TheRepairOrderToDelete'),
          // this.$ts('MaterialInventoryBrowsing'),
        ],
        dbBarMenuList: [
          this.$ts('edit'),
          this.$ts('Delete'),
          this.$ts('ViewTheClassScheduleInformation'),
        ],
        popupList: [
          { key: 'row_id', value: this.$ts('productionLines') },
          {
            key: 'WorkOrder',
            value: this.$ts('WorkOrder'),
          },
          {
            key: 'ProductsCode',
            value: this.$ts('model'),
          },
          {
            key: 'WorkingStartTime',
            value: this.$ts('startTime'),
            format: function (val) {
              return dayjs(val).format('YYYY-MM-DD HH:mm')
            },
          },
          {
            key: 'WorkingEndTime',
            value: this.$ts('endTime'),
            format: function (val) {
              return dayjs(val).format('YYYY-MM-DD HH:mm')
            },
          },
          {
            key: 'DeadLine',
            value: this.$ts('ShippingDate'),
            format: function (val) {
              return val ? dayjs(val).format('YYYY-MM-DD') : ''
            },
          },
          { key: 'WorkQty', value: this.$ts('WorkingOdd') },
          { key: 'Reduce', value: this.$ts('NumberOfCompleted') },
          {
            key: 'SfcCount',
            value: this.$ts('SFCSOutput'),
          },
          {
            key: 'SapCount',
            value: this.$ts('CompleteTheSAPNumber'),
          },
          { key: 'UPH', value: this.$ts('UPH') },
          {
            key: 'Remark',
            value: this.$ts('remarks'),
          },
          {
            key: 'Detail',
            value: this.$ts('OutputDetails'),
            columns: [
              {
                key: 'WorkDate',
                title: this.$ts('Date'),
                format: (val) => {
                  return dayjs(val).format('YYYY-MM-DD')
                },
              },
              {
                key: 'ShiftType',
                title: this.$ts('Shift'),
                format: (val) => {
                  if (val == undefined || val == '-1') return '/'
                  return [this.$ts('DayShift'), this.$ts('NightShift')][val]
                },
              },
              { key: 'Qty', title: this.$ts('ExpectedOutputDetails') },
            ],
          },
        ],
      }
      default_options = Object.assign({}, default_options, options)
      console.log("🚀 ~ init ~ default_options:", default_options)
      try {
        this.gantt = new Gantt(
          this.$refs.gantt,
          this.maskList,
          this.workhours,
          this.rows,
          default_options
        )
      } catch (err) {
        console.log(err)
        this.$message.error('gantt init error')
      }
    },
    // 获取我的方案
    getPlanOptions() {
      this.http.get(this.$api.leanLine + 'GetLinePlanList', {
        parentId: 0,
      }).then(async (r) => {
        this.planList = r.Data.map((v) => {
          return {
            label: v.LinePlanName,
            value: v.Id,
          }
        })
      })
    },
    //切换线体方案
    async dropDown(value) {
      this.gantt.hide_popup()
      if (value != 0 && this.needSave) {
        var res = await this.$confirm(this.$ts('schedulingChecked'))
        if (res != 'confirm') return
      }
      if (value == 0) {
        //管理我的方案
        this.$refs.planDialog.sendSortable()
        this.planDialog = true
      } else if (value == 1) {
        //清空方案选择
        this.currentPlan = {}
        this.rows = this.lineCodeOptions.map((x) => {
          return {
            id: x.value,
            row_id: x.value,
            name: x.value,
          }
        })
        this.undoList = []
        this.CanuUndo = false
        await this.GetGanttChartData()
      } else {
        const tmp = this.planList.find((x) => x.value == value)
        this.currentPlan = tmp
        this.currentPlan = tmp || {}
        //切换方案
        this.pageLoading = true
        const { Data } = await this.http.get(
          this.$api.leanLine + 'GetLinePlanList',
          { parentId: this.currentPlan.value }
        )
        this.pageLoading = false
        this.rows = Data.map((x) => {
          return {
            id: x.LineCode,
            row_id: x.LineCode,
            name: x.LineCode,
          }
        })
        if (this.rows.length == 0) {
          return this.$message.error(this.$ts('pleaseAddLine'))
        }
        this.undoList = []
        this.CanuUndo = false
        await this.GetGanttChartData()
      }
    },
    //移动工单
    async moveData(from, to, isLeft, isMulit) {
      this.$confirm(this.$ts('confirmOperate'))
        .then(async (r) => {
          if (r == 'confirm') {
            let moveData = [],
              oldMoveData = []
            var tmpToData = _.cloneDeep(to)
            var tmpFromData = _.cloneDeep(from)
            // if (!from || !to) return
            // if (from.id == to.id) return

            if (isMulit) {
              // this.taskMulitp
              this.taskMulitp.sort(
                (a, b) => dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
              )
              try {
                let query = {
                  tasks: this.taskMulitp,
                  lineCode: tmpToData.LineCode,
                }
                await this.http.post(
                  this.$api.schedue + 'CheckWorkOrderLine',
                  query,
                )
              } catch (error) {
                this.gantt.multipleList_clear()
                this.gantt.unselect_all()
                return
              }
              let toList = this.maskList
                .filter((x) => x.LineCode == tmpToData.LineCode)
                .sort(
                  (a, b) => dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
                )
              let fromList = this.maskList
                .filter((x) => x.LineCode == this.taskMulitp[0].LineCode)
                .sort(
                  (a, b) => dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
                )

              let deleteList = this.taskMulitp.map((x) =>
                x.WorkOrder.toString()
              )

              fromList = fromList.filter(
                (x) => !deleteList.includes(x.WorkOrder)
              )
              fromList.forEach((x, index) => (x.Seq = index + 1))
              this.taskMulitp.forEach((x) => (x.LineCode = tmpToData.LineCode))
              let otherToIndex = toList.findIndex(
                (x) => x.WorkOrder == tmpToData.WorkOrder
              )
              let sameLine = fromList[0].LineCode == tmpToData.LineCode

              // 优先清除掉线体移动的数据后进行otherToIndex去除
              if (sameLine) {
                for (let i = 0; i < this.taskMulitp.length; i++) {
                  let sameDeleteIndex = toList.findIndex(
                    (x) => x.WorkOrder == this.taskMulitp[i].WorkOrder
                  )
                  toList.splice(sameDeleteIndex, 1)
                  if (sameDeleteIndex < otherToIndex) otherToIndex -= 1
                }
              }
              for (let i = 0; i < this.taskMulitp.length; i++) {
                if (isLeft) {
                  toList.splice(
                    otherToIndex + i,
                    0,
                    _.cloneDeep(this.taskMulitp[i])
                  )
                } else {
                  toList.splice(
                    otherToIndex + i + 1,
                    0,
                    _.cloneDeep(this.taskMulitp[i])
                  )
                }
              }

              if (sameLine) {
                moveData = moveData.concat(toList)
              } else {
                moveData = moveData.concat(fromList).concat(toList)
              }
              moveData.forEach((x, index) => {
                x.Seq = index + 1
              })
            } else {
              if (tmpToData.LineCode == tmpFromData.LineCode) {
                moveData = this.maskList
                  .filter((x) => x.LineCode == tmpToData.LineCode)
                  .sort(
                    (a, b) =>
                      dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
                  )
                oldMoveData = _.cloneDeep(moveData)
                let fromIndex = oldMoveData.findIndex(
                  (x) => x.WorkOrder == tmpFromData.WorkOrder
                )
                moveData = moveData.splice(fromIndex, 1)
                oldMoveData = oldMoveData.splice(fromIndex, 1)
                let toIndex = oldMoveData.findIndex(
                  (x) => x.WorkOrder == tmpToData.WorkOrder
                )
                if (isLeft) {
                  moveData.splice(toIndex, 0, _.cloneDeep(tmpFromData))
                } else {
                  moveData.splice(toIndex + 1, 0, _.cloneDeep(tmpFromData))
                }

                moveData.forEach((x, index) => {
                  x.Seq = index + 1
                })
              } else {
                try {
                  let query = {
                    tasks: [_.cloneDeep(tmpFromData)],
                    lineCode: tmpToData.LineCode,
                  }
                  await this.http.post(
                    this.$api.schedue + 'CheckWorkOrderLine',
                    query,
                  )
                } catch (error) {
                  return
                }
                let toList = this.maskList
                  .filter((x) => x.LineCode == tmpToData.LineCode)
                  .sort(
                    (a, b) =>
                      dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
                  )
                let fromList = this.maskList
                  .filter((x) => x.LineCode == tmpFromData.LineCode)
                  .sort(
                    (a, b) =>
                      dayjs(a.start).valueOf() > dayjs(b.start).valueOf()
                  )
                let otherFromIndex = fromList.findIndex(
                  (x) => x.WorkOrder == tmpFromData.WorkOrder
                )
                fromList.splice(otherFromIndex, 1)
                fromList.forEach((x, index) => (x.Seq = index + 1))
                tmpFromData.LineCode = tmpToData.LineCode
                let otherToIndex = toList.findIndex(
                  (x) => x.WorkOrder == tmpToData.WorkOrder
                )
                if (isLeft) {
                  toList.splice(otherToIndex, 0, _.cloneDeep(tmpFromData))
                } else {
                  toList.splice(otherToIndex + 1, 0, _.cloneDeep(tmpFromData))
                }
                toList.forEach((x, index) => (x.Seq = index + 1))
                moveData = moveData.concat(toList).concat(fromList)
              }
            }
            this.Rearrangement(moveData, null, false, false, 1)
            this.gantt.multipleList_clear()
            this.gantt.hide_popup()
            this.gantt.unselect_all()
          }
        })
        .catch()
    },

    //重排数据请求
    Rearrangement(tasks, lines, isAll = false, isUndo = false, type = 0) {
      if (lines == null || lines.length == 0) {
        lines = _.uniq(tasks.map((x) => x.LineCode))
      }
      this.pageLoading = true
      this.http.post(
        this.$api.schedue + 'ApsScheduleTaskRearrangement',
        { oldTasks: tasks, lines, type },
      )
        .then((r) => {
          this.$message.success(this.$ts('success'))
          this.getRowData(r.Data, isAll, isUndo)
          this.pageLoading = false
        })
        .catch((r) => {
          this.pageLoading = false
        })
    },

    //重排数据请求
    Rearrangement(tasks, lines, isAll = false, isUndo = false, type = 0) {
      if (lines == null || lines.length == 0) {
        lines = _.uniq(tasks.map((x) => x.LineCode))
      }
      this.pageLoading = true
      this.http.post(
        this.$api.schedue + 'ApsScheduleTaskRearrangement',
        { oldTasks: tasks, lines, type },
      )
        .then((r) => {
          let error = []
          if (
            r.Data.DeletedScheduleTasks &&
            r.Data.DeletedScheduleTasks.length > 0
          ) {
            error = r.Data.DeletedScheduleTasks.map((v) => {
              return v.WorkOrder + ':' + v.Message
            })
            this.deletedScheduleTasks = this.deletedScheduleTasks.concat(
              r.Data.DeletedScheduleTasks
            )
          }
          this.$message.success(
            this.$ts('success') +
              ':' +
              (error.length > 0 ? error.join(';') + '被移除排程' : '')
          )
          this.getRowData(r.Data, isAll, isUndo)
          this.pageLoading = false
        })
        .catch((r) => {
          this.pageLoading = false
        })
    },
    // 切换table图
    goToSchedulingTable() {
      if (this.muliBoxList.length == 0) {
        return this.$message.error(this.$ts('PleaseSelectASolidBody'))
      }
      this.$router.push({
        path:
          '/ManualScheduling/ManualSchedulingTable?LineCode=' +
          this.muliBoxList[this.muliBoxList.length - 1],
      })
    },
    //重新计算
    recalculate() {
      if (this.muliBoxList.length == 0) {
        return this.$message.error(this.$ts('PleaseSelectASolidBody'))
      }
      //  else if (this.muliBoxList.length > 1) {
      //   return this.$message.error(this.$ts('ThereCanBeAtMostOneSolidLine'))
      // }
      this.reCalculateLines(this.muliBoxList)
    },
    //直接重新计算某些线的数据
    reCalculateLines(lines, isAll = false, uniq = false) {
      if (lines.length == 0) return
      let arr = this.maskList.filter((x) => lines.includes(x.LineCode))
      this.Rearrangement(arr, lines, isAll, uniq, 1)
    },
    //放大缩小
    zoomChange(add) {
      let tmp = this.viewModes.findIndex((x) => x == this.currentView)
      tmp = tmp + (add ? -1 : 1)
      if (tmp < 0) {
        return this.$message.warning(this.$ts('pleaseMAX'))
      }
      if (tmp >= this.viewModes.length) {
        return this.$message.warning(this.$ts('pleaseMIN'))
      }
      this.currentView = this.viewModes[tmp]

      this.gantt.change_view_mode(this.currentView)
    },
    vueSetScroll(e) {
      // this.$refs.left.scrollTop = e.target.scrollTop
    },
    //行事历右键菜单
    menuClickHandle(index, name, task, barType, e) {
      if (name == 'barMenu' && barType == 1) {
        switch (index) {
          case 0:
            this.editSchedule(task, task.ShiftType)
            break
          case 1:
            this.deleteSchedule(task)
            break
          case 2:
            this.showSchedule(task)
            break

          default:
            break
        }
      } else if (name == 'barMenu' && barType == 2) {
        switch (index) {
          // case 0:
          //   this.$prompt(this.$ts('AdjustTheUPH'), '', {
          //     inputValue: task.UPH || 0,
          //   })
          //     .then(({ value, action }) => {
          //       if (action == 'confirm') {
          //         this.maskList.find((x) => x.Id == task.Id).UPH = value
          //         let arr = this.maskList.filter(
          //           (x) => x.LineCode == task.LineCode
          //         )
          //         this.Rearrangement(arr)
          //       }
          //     })
          //     .catch(() => {})
          //   break
          case 0:
            this.$prompt(
              this.$ts('confirmRemoveThisWork'),
              this.$ts('WorkOrderRemovalConfirmation'),
              {
                confirmButtonText: this.$ts('confirm1'),
                cancelButtonText: this.$ts('cancel1'),
                inputValue: '',
                inputPlaceholder: this.$ts('PleaseEnterTheReasonForRemoval'),
              }
            )
              .then(({ value, action }) => {
                if (action == 'confirm') {
                  this.Remark = value
                  this.deleteTask(task)
                }
              })
              .catch()
            break

          default:
            break
        }
      } else if (name == 'Menu') {
      }
      // if (name == 'barMenu' && index == 1) {

      // }
    },
    search() {
      this.pageLoading = true
      let taskList = _.cloneDeep(this.maskList)
      if (this.form.select) {
        taskList = taskList.filter((x) => x.LineCode == this.form.select)
      }
      if (this.form.workOrder) {
        taskList = taskList.filter(
          (x) => x.WorkOrder.indexOf(this.form.workOrder) != -1
        )
      }
      if (this.form.code) {
        taskList = taskList.filter(
          (x) => x.ProductsCode.indexOf(this.form.code) != -1
        )
      }
      this.gantt.search_all(taskList)
      this.pageLoading = false
    },
    //甘特图左侧的线体选择变化事件
    boxChange(value, item) {
      let index = this.muliBoxList.findIndex((x) => x == item.id)
      if (value) {
        if (index == -1) this.muliBoxList.push(item.id)
      } else {
        if (index != -1) this.muliBoxList.splice(index, 1)
      }
    },
    popupMoreClick(item, type) {
      if (type == 0) {
        this.$prompt(
          this.$ts('settingIsUsedForSAP'),
          this.$ts('ModifyTheShippingDate'),
          {
            inputValue: item.DeadLine
              ? dayjs(item.DeadLine).format('YYYY-MM-DD')
              : '',
          }
        )
          .then(({ value, action }) => {
            if (action == 'confirm') {
              let datetmp = null
              try {
                datetmp = this.dayjs(value, 'YYYY-MM-DD')
              } catch (e) {
                this.$message.error(this.$ts('TheDateFormatIsIncorrect'))
                return
              }
              if (datetmp == null || !datetmp.isValid()) {
                this.$message.error(this.$ts('TheDateFormatIsIncorrect'))
                return
              }

              item.DeadLine = datetmp
              this.http.post(this.$api.schedue + 'UpdateDeadLine', item)
                .then((r) => {
                  this.undoList = []
                  this.CanuUndo = false
                  this.$message.success(this.$ts('success'))
                  let index = this.maskList.findIndex((x) => x.Id == r.Id)
                  r.Data.id = r.Data.Id
                  r.Data.start = r.Data.WorkingStartTime
                  r.Data.end = r.Data.WorkingEndTime
                  r.Data.row_id = r.Data.LineCode
                  r.Data.barType = 2
                  r.Data.custom_class = 'bar-milestone'
                  r.Data.Detail =
                    this.taskDate.filter((l) => l.TaskId == r.Data.Id) || []
                  this.maskList.splice(index, 1, r.Data)
                  this.gantt.unselect_all()
                  this.gantt.hide_popup()
                  this.gantt.refresh_rows(
                    this.maskList,
                    [],
                    [r.Data.LineCode],
                    [2]
                  )
                  //TODO 此处调用一下重新计算接口
                  // this.reCalculateLines([item.LineCode])
                })
                .catch()
            }
          })
          .catch(() => {})
      } else if (type == 1) {
        this.$prompt(this.$ts('AdjustTheUPH'), '', {
          inputValue: item.UPH || 0,
        })
          .then(({ value, action }) => {
            if (action == 'confirm') {
              this.maskList.find((x) => x.Id == item.Id).UPH = value
              let arr = this.maskList.filter((x) => x.LineCode == item.LineCode)
              this.undoList = []
              this.CanuUndo = false
              this.Rearrangement(arr, [], false, true)
            }
          })
          .catch(() => {})
      } else if (type == 2) {
        this.$prompt('请输入备注', '提示', {
          inputValue: item.Remark,
        }).then(({ value }) => {
          item.Remark = value
          this.http.post(
            this.$api.schedue + 'UpdateDeadLine',
            item,
          ).then((r) => {
            this.undoList = []
            this.CanuUndo = false
            this.$message.success(this.$ts('success'))
            try {
              this.gantt.hide_popup()
            } catch (error) {}
            let index = this.maskList.findIndex((x) => x.Id == r.Data.Id)
            r.Data.id = r.Data.Id
            r.Data.start = r.Data.WorkingStartTime
            r.Data.end = r.Data.WorkingEndTime
            r.Data.row_id = r.Data.LineCode
            r.Data.barType = 2
            r.Data.custom_class = 'bar-milestone'
            r.Data.Detail =
              this.taskDate.filter((l) => l.TaskId == r.Data.Id) || []
            this.maskList.splice(index, 1, _.cloneDeep(r.Data))
            this.gantt.refresh_rows(this.maskList, [], [item.LineCode], [2])
          })
        })
      }
    },
    // 多选数据处理
    selectFormDatas(val) {
      this.taskMulitp = val
    },
    // 获取我管理的线体
    async getMyLineCode() {
      await this.http.get(this.$api.leanLine + 'GetMyLineList', {
        page: 1,
        size: 9999,
      }).then((r) => {
        this.lineCodeOptions = r.Data.map((x) => {
          return {
            label: x.LineCode,
            value: x.LineCode,
          }
        })
      })
    },
    errorMessage() {
      this.$message.error(
        this.$ts('MultipleSelectionOperationsCannotCrossLines')
      )
    },
    // 导入数据
    excelSucces(data) {
      this.getRowData(data, false, true)
    },
    // 增加工单更替数据
    async getRowData(data, isAll = false, isUndo) {
      try {
        let {
          tasks,
          taskDates,
          lines,
          halbCalWorkOrders,
          halbCalWoComponents,
          halbCalInventorys,
        } = data
        if (!lines || lines.length == 0) {
          lines = Array.from(new Set(tasks.map((x) => x.LineCode)))
        }
        if (!isUndo) {
          this.undoList.push({
            maskList: _.cloneDeep(this.maskList),
            taskDate: _.cloneDeep(this.taskDate),
          })
          this.CanuUndo = true
        }
        tasks.forEach((x) => {
          x.id = x.Id
          x.start = x.WorkingStartTime
          x.end = x.WorkingEndTime
          x.row_id = x.LineCode
          x.barType = 2
          x.custom_class = 'bar-milestone'
          x.Detail = taskDates.filter((l) => l.TaskId == x.Id) || []
          x.WorkDate = x.Detail.length > 0 ? x.Detail[0].WorkDate : null
        })
        this.maskList = this.maskList.filter((x) => !lines.includes(x.LineCode))
        this.maskList = this.maskList.concat(tasks)
        this.taskDate = this.taskDate.filter((x) => !lines.includes(x.LineCode))
        //.filter((c) => c instanceof Object)
        this.taskDate = this.taskDate.concat(taskDates)

        if (halbCalWorkOrders && halbCalWorkOrders.length > 0)
          this.halbCalWorkOrders = this.arrayCombine(
            this.halbCalWorkOrders,
            halbCalWorkOrders,
            'WorkOrder'
          )
        if (halbCalWoComponents && halbCalWoComponents.length > 0)
          this.halbCalWoComponents = this.arrayCombine(
            this.halbCalWoComponents,
            halbCalWoComponents,
            'Id'
          )
        if (halbCalInventorys && halbCalInventorys.length > 0)
          this.halbCalInventorys = this.arrayCombine(
            this.halbCalInventorys,
            halbCalInventorys,
            'MaterialCode'
          )
        this.gantt.unselect_all()
        this.gantt.hide_popup()
        if (isAll) {
          try {
            let url = this.$api.schedue + 'GetLineCalendarByLines'
            let tmp = {
              lineCodes: lines,
              beginDate: this.gantt.gantt_start,
              endDate: this.gantt.gantt_end,
            }
            let { Data } = await this.http.post(url, tmp)
            //行事历数据处理
            Data.forEach((x) => {
              x.id = x.Id
              x.start = x.ShiftType
                ? dayjs(x.WorkDate)
                    .add(12, 'hours')
                    .format('YYYY-MM-DD HH:mm:ss')
                : x.WorkDate
              x.end = dayjs(x.start)
                .add(12, 'hours')
                .format('YYYY-MM-DD HH:mm:ss')
              x.row_id = x.LineCode
              x.barType = 1
              x.selectStatus = true
              x.custom_class = 'bar-milestone'
            })
            // 去除合并改线体的所有行事历
            this.workhours = this.workhours.filter(
              (x) => !lines.includes(x.LineCode)
            )
            this.workhours = this.workhours.concat(Data)
          } catch (error) {
            console.log('获取行事历失败')
          }
        }
        if (isAll) {
          this.gantt.refresh_rows(this.maskList, this.workhours, lines, [1, 2])
        } else {
          this.gantt.refresh_rows(this.maskList, [], lines, [2])
        }
        if (this.taskMulitp.length > 0) {
          this.gantt.multipleList_clear()
        }
        this.needSave = true
      } catch (e) {
        console.error(e)
      }
    },
    arrayCombine(array1, array2, key) {
      let combinedArray = [...array1]
      array2.forEach((obj2) => {
        const index = combinedArray.findIndex((obj1) => obj1[key] === obj2[key])
        if (index !== -1) {
          combinedArray[index] = { ...combinedArray[index], ...obj2 }
        } else {
          combinedArray.push(obj2)
        }
      })
      return combinedArray
    },
    // 删除工单
    deleteTask(task) {
      this.canDeleteTask.push({
        WorkOrder: task.WorkOrder,
        Remark: this.Remark,
      })
      let changeList = this.maskList
        .filter((x) => x.row_id == task.row_id)
        .sort((a, b) => dayjs(a.start).valueOf() > dayjs(b.start).valueOf())
      let index = changeList.findIndex((x) => x.WorkOrder == task.WorkOrder)
      if (index != -1) changeList.splice(index, 1)
      changeList.forEach((x, index) => (x.Seq = index + 1))
      this.taskDate = this.taskDate.filter((x) => x.WorkOrder != task.WorkOrder)
      this.Rearrangement(changeList, [task.LineCode])
    },
    // 保存数据
    SaveApsScheduleTask() {
      if (!this.needSave) return this.$message.info('没有需要保存的数据')
      this.pageLoading = true
      let data = {
        newtasks: this.maskList,
        newtaskDates: this.taskDate,
        deletes: this.canDeleteTask,
        lines: this.rows.map((x) => x.id),
        ApsScheduleId: this.currentVersion.value,
        halbCalWoComponents: this.halbCalWoComponents,
        halbCalInventorys: this.halbCalInventorys,
        halbCalWorkOrders: this.halbCalWorkOrders,
        deletedScheduleTasks: this.deletedScheduleTasks,
      }
      this.http.post(this.$api.schedue + 'SaveApsScheduleTask', data)
        .then(async (r) => {
          this.halbCalWoComponents = []
          this.halbCalInventorys = []
          this.halbCalWorkOrders = []
          this.deletedScheduleTasks = []
          this.$message.success(this.$ts('success'))
          this.needSave = false
          // this.rows = this.lineCodeOptions.map((x) => {
          //   return {
          //     id: x.value,
          //     row_id: x.value,
          //     name: x.value,
          //   }
          // })
          await this.GetGanttChartData()
          this.pageLoading = false
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    // 显示达成率统计对话框
    ShowPercentDialog() {
      this.calculatedAchievementRate()
      this.percentDialogShow = true
    },
    // 自动排序
    ApsScheduleTaskSort() {
      if (this.muliBoxList.length == 0) {
        return this.$message.info(this.$ts('SelectTheSolidLineBeforeOperation'))
      }
      let taskList = this.maskList.filter((x) =>
        this.muliBoxList.includes(x.LineCode)
      )
      if (taskList.length == 0) {
        return this.$message.info(
          this.$ts('NoWorkOrderNeedsToBeSynchronizedOnTheSolidLine')
        )
      }
      this.autoSortVisibleDialog = true
    },
    autoSortAps() {
      if (!this.autoSortDateStartTime)
        return this.$message.info(this.$ts('PleaseSelectADateToSort'))

      let taskList = this.maskList.filter((x) =>
        this.muliBoxList.includes(x.LineCode)
      )
      this.autoSortLoading = true
      this.http.post(
        this.$api.schedue + 'ApsScheduleTaskSort',
        {
          WorkDate: this.autoSortDateStartTime,
          oldTasks: taskList,
        },
      )
        .then((r) => {
          this.$message.success(this.$ts('success'))
          this.getRowData(r.Data, false, false)
          this.autoSortLoading = false
          this.autoSortVisibleDialog = false
        })
        .catch((r) => {
          this.autoSortLoading = false
        })
    },
    // 因修改gantt图重新获取数据
    async refreshGanttData() {
      this.pageLoading = true
      await this.GetGanttChartData()
    },
    //点击生成行事历
    addSchedule() {
      this.scheduleBatchAddVisible = true
      const lineCode =
        this.muliBoxList.length > 0
          ? this.muliBoxList[this.muliBoxList.length - 1]
          : ''
      this.addScheduleData = {
        Weeks: [],
        NLostRate: 100,
        DLostRate: 100,
        LineCode: lineCode,
      }
    },
    //生成行事历提交完成后的操作
    afterAddSchedule(data) {
      this.undoList = []
      this.CanuUndo = false
      let arr = []
      if (data.LineCode) {
        arr.push(data.LineCode)
      }
      if (
        data.NewLineCode &&
        typeof data.NewLineCode == 'string' &&
        !arr.includes(data.NewLineCode)
      ) {
        console.log(data.NewLineCode, '我进来了')
        arr.push(data.NewLineCode)
      } else if (data.NewLineCode && data.NewLineCode instanceof Array) {
        data.NewLineCode.forEach((x) => {
          if (!arr.includes(x)) arr.push(x)
        })
      }
      console.log(data, arr, 'testdata')
      this.reCalculateLines(arr, true, true)
    },
    //编辑行事历
    async editSchedule(item, type) {
      try {
        await this.$refs.scheduleBatchEdit.getEditScheduleList(type)
        this.http.get(this.$api.calendar + 'GetById', { Id: item.Id }).then(
          (r) => {
            r.Data.WorkDate = dayjs(r.Data.WorkDate).format('YYYY-MM-DD')
            this.editScheduleData = _.cloneDeep(r.Data)
            this.scheduleBatchEditVisible = true
          }
        )
      } catch (e) {}
    },
    //点击行事历互调
    togetherSchedule() {
      this.togetherScheduleData = {}
      this.scheduleBatchTogetherVisible = true
    },
    // 点击行事历批量删除
    deleteMoreSchedule() {
      const lineCode =
        this.muliBoxList.length > 0
          ? this.muliBoxList[this.muliBoxList.length - 1]
          : ''
      this.deleteScheduleData = {
        LineCode: lineCode,
      }
      this.scheduleBatchDeleteVisible = true
    },
    // 展示班次明细
    showSchedule(task) {
      this.$nextTick(async () => {
        try {
          let { Data } = await this.http.get(
            this.$api.schedule + 'GetDetailList',
            {
              page: 1,
              size: 9999,
              ScheduleId: task.ScheduleId,
            }
          )
          this.scheduleList = Data
          this.showVisibleDialog = true
        } catch (error) {}
      })
    },
    // 新建工单
    addWorkOrder() {
      if (this.muliBoxList.length == 0) {
        return this.$message.info(this.$ts('PleaseSelectASolidBody'))
      } else if (this.muliBoxList.length > 1) {
        return this.$message.info(this.$ts('ThereCanBeAtMostOneSolidLine'))
      }
      this.$nextTick(() => {
        this.$refs.zTableAddProject.changeQuery({
          linecode: this.muliBoxList[0],
          productType: '',
          page: 1,
          size: 10,
          isAdd: 'N',
          workorder: '',
        })
        this.addWorkOrderFormVisible = true
      })
    },
    // 删除单个行事历中的班表
    deleteSchedule(v) {
      this.$confirm(this.$ts('cfmDelete'), this.$ts('oprConfirm'))
        .then(() => {
          this.pageLoading = true
          let url = this.$api.calendar + 'delete'
          this.http.post(url + '/' + v.Id, { id: v.Id })
            .then((r) => {
              this.$message.success(this.$ts('success'))
              this.afterAddSchedule(v)
            })
            .finally(() => {
              this.pageLoading = false
            })
        })
        .catch(() => {})
    },
    // 点击跨线重排
    acrossLineGantt() {
      if (this.muliBoxList.length <= 1) {
        return this.$message.info('请选择多条实体线后再操作')
      }
      this.crossScheduleData = {
        oldTasks: this.maskList.filter((x) =>
          this.muliBoxList.includes(x.LineCode)
        ),
        lines: this.muliBoxList,
      }
      this.scheduleBatchCrossVisible = true
    },
    // 展示班表明细
    barTypeOneClick(row) {
      console.log(row)
      this.foremanDetailRow = _.cloneDeep(row)
      this.foremanDetailVisible = true
    },

    // 导出数据
    exportData() {
      this.exporting = true
      this.http.post(
        this.$api.schedue + 'GetScheduleTableExport',
        {
          ApsScheduleId: this.exportSelectedVersion,
          lineCodes: this.exportSelectedLines || [],
          AreaId: this.exportSelectedArea || 0,
        },
      )

        .then((r) => {
          this.exporting = false
          this.calDataAndExcel(r.Data)
          this.exportDialogVisible = false
          this.exportInputModel = ''
          this.exportSelectedArea = ''
          this.exportSelectedLines = []
        })
        .catch((err) => {
          console.error(err)
          // this.refreshTable([], [])
          this.exporting = false
          this.tableLoading = false
        })
    },
    calDataAndExcel(data) {
      let { taskDates, tasks, lineCalendars, restDays } = data
      let classArray = []
      lineCalendars.forEach((x) => {
        if (
          !classArray.some(
            (c) => c.day == x.WorkDate && c.ShiftType.includes(x.ShiftType)
          )
        ) {
          if (classArray.some((l) => l.day == x.WorkDate)) {
            let index = classArray.findIndex((k) => k.day == x.WorkDate)
            if (!classArray[index].ShiftType.includes(x.ShiftType)) {
              classArray[index].ShiftType.push(x.ShiftType)
            }
          } else {
            classArray.push({
              day: x.WorkDate,
              ShiftType: [x.ShiftType],
            })
          }
        }
      })
      if (classArray.length) {
        // 将非工作日的workDate传递进入
        restDays.forEach((x) => {
          classArray.push({
            day: x,
            ShiftType: [],
          })
        })
        // 进行排序
        classArray.sort(
          (a, b) =>
            parseInt(dayjs(a.day).valueOf()) - parseInt(dayjs(b.day).valueOf())
        )
        // 筛除超过最大休息日
        let maxDate = dayjs(
          lineCalendars[lineCalendars.length - 1].WorkDate
        ).valueOf()
        classArray = classArray.filter(
          (x) => dayjs(x.day).valueOf() - maxDate <= 0
        )
      }

      let titles = classArray.map((i) => {
        let key = dayjs(i.day).format('MM-DD')
        let classStr = `(${i.ShiftType.includes(0) ? 'D' : ''}${
          i.ShiftType.includes(1) ? 'N' : ''
        })`
        return { label: key + (classStr.length == 2 ? '' : classStr), key }
      })
      const titlesFixed = [
        { label: this.$ts('Line'), key: 'LineCode' },
        { label: this.$ts('model'), key: 'ProductsCode' },
        { label: this.$ts('WorkOrder'), key: 'WorkOrder' },
        { label: this.$ts('Online'), key: 'WorkingStartTime' },
        { label: this.$ts('CompletionDate'), key: 'WorkingEndTime' },
        { label: this.$ts('TheShipmentDate'), key: 'DeadLine' },
        { label: this.$ts('number'), key: 'WorkQty' },
        // { label: this.$ts('NumberOfCompleted'), key: 'Reduce' },
        { label: this.$ts('TheSAPNumber'), key: 'SapCount' },
        { label: this.$ts('TheSFCNumber'), key: 'SfcCount' },
        { label: this.$ts('UPH'), key: 'UPH' },
        { label: this.$ts('IsNew'), key: 'IsNew' },
        { label: this.$ts('remarks'), key: 'Remark' },
      ]
      //时间格式处理
      tasks.forEach((i) => {
        i.WorkingEndTime = i.WorkingEndTime
          ? this.dayjs(i.WorkingEndTime).format('YYYY-MM-DD HH:mm')
          : ''
        i.WorkingStartTime = i.WorkingStartTime
          ? this.dayjs(i.WorkingStartTime).format('YYYY-MM-DD HH:mm')
          : ''
        i.DeadLine = i.DeadLine
          ? this.dayjs(i.DeadLine).format('YYYY-MM-DD')
          : ''
        i.IsNew = i.IsNew ? this.$ts('yes') : this.$ts('no')
        let tmpList = taskDates.filter((c) => c.WorkOrder == i.WorkOrder)
        titles.forEach((x) => {
          let tmp = 0
          if (tmpList.length) {
            tmpList
              .filter((el) => dayjs(el.WorkDate).format('MM-DD') == x.key)
              .forEach((numberX) => {
                tmp += numberX.Qty
              })
            // tmp = tmpList.find(
            //   (c) => dayjs(c.WorkDate).format('MM-DD') == x.key
            // )
          }
          i[x.key] = tmp ? tmp : ''
        })
      })
      titles = titlesFixed.concat(titles)
      let fileName = '排程导出-' + this.dayjs().format('YYYYMMDDHHmm')
      // 开始导出xlsx
      let workbook = XLSX.utils.book_new()

      // 展示名称
      let header = {}
      for (let i = 0; i < titles.length; i++) {
        const item = titles[i]
        header[item.key] = item.label
      }
      let sheetData = []
      tasks.forEach((x) => {
        let tmp = {}
        for (let key in header) {
          tmp[key] = x[key]
        }
        sheetData.push(_.cloneDeep(tmp))
      })

      // 数据源
      const sheet = [header, ...sheetData]

      let ws = XLSX.utils.json_to_sheet(sheet, {
        // 跳过 Header, 就是把原来表格数据的表头去掉了, headerReplace渲染的数据 "冒充" 表头了
        skipHeader: true,
      })
      // 处理样式
      ws['!cols'] = [{ wch: 15 }, { wch: 15 }, { wch: 15 }]
      const borderAll = {
        //单元格外侧框线
        top: {
          style: 'thin',
        },
        bottom: {
          style: 'thin',
        },
        left: {
          style: 'thin',
        },
        right: {
          style: 'thin',
        },
      }
      try {
        const wsNames = Object.keys(ws)
        let forEachArr = wsNames.filter((x) => /[A-Z]{1}1$/.test(x))
        let setColorArrStr = forEachArr
          .filter((x) => /[0-1]\d-[0-3]\d$/.test(ws[x].v))
          .map((x) => x.replace(/\d/, ''))
        // 设置需要设置的背景色
        setColorArrStr.forEach((x) => {
          for (let i = 2; i < tasks.length + 2; i++) {
            ws[x + i].s = {
              fill: { fgColor: { rgb: 'FFE7BB' } },
              // border: borderAll,
              alignment: {
                horizontal: 'center',
                vertical: 'center',
              },
            }
          }
        })
        // // 头部颜色
        forEachArr.forEach((x) => {
          ws[x].s = {
            fill: { fgColor: { rgb: '999999' } },
            // border: borderAll,
            alignment: {
              horizontal: 'center',
              vertical: 'center',
            },
          }
        })
      } catch (error) {
        console.log(error)
        this.$message.error('导出失败')
      }

      XLSX.utils.book_append_sheet(workbook, ws, 'Sheet1')
      let wbout = XLSXS.write(workbook, {
        // 使用 xlsx-style 中的write方法
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary',
      })
      FileSaver.saveAs(
        new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' }),
        fileName + '.xlsx'
      )
    },
    s2ab(s) {
      var buf = new ArrayBuffer(s.length)
      var view = new Uint8Array(buf)
      for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
      return buf
    },
    // 快照点击
    snapShotChange(v) {
      switch (v) {
        case 0:
          this.saveSnapShot()
          break
        case 1:
          this.snapshotShowDialog = true
          break
        // case 2:
        //   this.calculatedAchievementRate()
        //   this.SnapshotComparisonShowDialog = true
        //   break
      }
    },
    // 保存快照
    saveSnapShot() {
      this.$prompt('请输入快照名称', '提示', {
        inputValue: '',
      })
        .then(({ value }) => {
          this.pageLoading = true
          let data = {
            ApsScheduleId: this.currentVersion.value,
            SnapName: value,
            newtasks: this.maskList,
            newtaskDates: this.taskDate,
          }
          this.http.post(this.$api.schedue + 'SaveApsScheduleSnap', data, 'post')
            .then((r) => {
              this.$message.success(this.$ts('success'))
              this.pageLoading = false
            })
            .catch(() => {
              this.pageLoading = false
            })
        })
        .catch(() => {})
    },
    // 处理快照数据
    afterSnapShotData(Data) {
      this.showLoadingOrRefresh = true
      Data.tasks.forEach((x) => {
        x.id = x.Id
        x.start = x.WorkingStartTime
        x.end = x.WorkingEndTime
        x.row_id = x.LineCode
        x.barType = 2
        x.custom_class = 'bar-milestone'
        x.Detail = Data.taskDates.filter((l) => l.TaskId == x.Id) || []
      })
      //行事历数据处理
      Data.lineCalendars.forEach((x) => {
        x.id = x.Id
        x.start = x.ShiftType
          ? dayjs(x.WorkDate).add(12, 'hours').format('YYYY-MM-DD HH:mm:ss')
          : x.WorkDate
        x.end = dayjs(x.start).add(12, 'hours').format('YYYY-MM-DD HH:mm:ss')
        x.row_id = x.LineCode
        x.barType = 1
        x.selectStatus = true
        x.custom_class = 'bar-milestone'
      })
      this.muliBoxList = [] //清空选中状态
      this.maskList = Data.tasks.filter((x) =>
        this.rows.map((c) => c.name).includes(x.LineCode)
      )
      this.workhours = Data.lineCalendars.filter((x) =>
        this.rows.map((c) => c.name).includes(x.LineCode)
      )
      this.taskDate = Data.taskDates.filter((x) =>
        this.rows.map((c) => c.name).includes(x.LineCode)
      )
      this.pageLoading = false
      let options = {
        IsEdit: this.currentVersion.IsEdit,
        Holidays: Data.restDays,
      }
      if (this.gantt) {
        this.gantt.unselect_all()
        this.gantt.refresh(this.maskList, this.workhours, this.rows, options)
      } else this.init(options)
      this.needSave = false
    },
    // 载入排程
    LoadSchedule() {
      try {
        this.LoadScheduleLoading = true
        this.gantt.refresh(this.maskList, this.workhours, this.rows, {
          IsEdit: true,
        })
        this.needSave = true
        this.showLoadingOrRefresh = false
        setTimeout(() => {
          this.LoadScheduleLoading = false
        }, 500)
      } catch (error) {
        this.LoadScheduleLoading = false
      }
    },
    // 还原排程
    ReductionSchedule() {
      try {
        this.ReductionScheduleLoading = true

        this.showLoadingOrRefresh = false
        this.versionChange(this.versionOptions[0].value)
      } catch (error) {
        this.ReductionScheduleLoading = false
      }
    },
    // 撤销
    undoSchedule() {
      try {
        this.pageLoading = true
        this.undoLoading = true
        let tmp = this.undoList[this.undoList.length - 1]
        this.maskList = _.cloneDeep(tmp.maskList)
        this.taskDate = _.cloneDeep(tmp.taskDate)
        this.undoList.pop()
        this.gantt.refresh_rows(
          this.maskList,
          [],
          Array.from(new Set(this.maskList.map((x) => x.LineCode))),
          [2]
        )
        if (this.undoList.length == 0) {
          this.CanuUndo = false
        }
        setTimeout(() => {
          this.pageLoading = false
          this.undoLoading = false
        }, 500)
      } catch (error) {
        this.pageLoading = false
        this.undoLoading = false
      }
    },

    // 邮件相关
    openEmailLineSelect() {
      this.emailexportDialogVisible = true
    },
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
}
</script>

<style lang="scss" scoped>
.right {
  height: 100%;
  width: 100%;
  overflow-y: auto;
}

.flex {
  .icon-btn {
    .icon {
      font-size: 16px;
    }
    .title {
      font-size: 12px;
    }
    width: 60px;
    min-height: 50px;
    background: #efefef;
    text-align: center;
    border-radius: 4px;
    cursor: pointer;
    margin: 0 5px 5px 0;
    padding-top: 6px;
  }
}
.no-margin .icon-btn {
  margin: 0;
  margin-left: 4px;
}

@import url('../../../uitils/gantt/frappe-gantt.css');
.ganttCss {
  width: calc(100% - 65px);
  height: 100%;
  transition: all 0.35s;
}

// ::v-deep .el-input {
//   width: 240px !important;
// }
::v-deep .el-col {
  margin-bottom: 10px;
}

::-webkit-scrollbar {
  display: none;
}

.lineHeight24 {
  line-height: 24px;
  margin-left: 4px;
}
</style>
